//
//  WSDiscoverCoverScrollView.h
//  BaseProject
//
//  Created by karong on 2023/6/13.
//

#import "WSDiscoverCoverScrollView.h"
#import "WSImageCell.h"
#import "WSImageTitleCell.h"

#define kCycleScrollViewInitialPageControlDotSize CGSizeMake(10, 10)

NSString * const ID = @"cycleCell";

typedef NS_ENUM(NSInteger, DragDirection) {
    DragDirectionNone,
    DragDirectionLeft,
    DragDirectionRight,
};

@interface WSDiscoverCoverScrollView () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, weak) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSArray *imagePathsGroup;
@property (nonatomic, weak) NSTimer *timer;
@property (nonatomic, assign) NSInteger totalItemsCount;
@property (nonatomic, weak) UIControl *pageControl;

@property (nonatomic, strong) UIImageView *backgroundImageView; // 當imageURLs為空時的背景圖

@property (assign, nonatomic) CGFloat contentOffsetX;  // collectionView偏移量
@property (assign, nonatomic) DragDirection dragDirection;  // 拖動方向
@property (assign, nonatomic) BOOL isDragging;  // 是否處於被拖動狀態

@end

@implementation WSDiscoverCoverScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initialization];
        [self setupMainView];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self initialization];
    [self setupMainView];
}

- (void)initialization {
    _pageControlAliment = WSDiscoverCoverScrollViewPageContolAlimentCenter;
    _autoScrollTimeInterval = 5.0;
    _titleLabelTextColor = [UIColor blackColor];
    _titleLabelTextFont= [UIFont systemFontOfSize:14];
    _titleLabelBackgroundColor = [UIColor clearColor];
    _titleLabelHeight = 30;
    _autoScroll = YES;
    _infiniteLoop = YES;
    _showPageControl = YES;
    _pageControlDotSize = kCycleScrollViewInitialPageControlDotSize;
    _pageControlBottomOffset = 0;
    _pageControlRightOffset = 0;
    _pageControlStyle = WSDiscoverCoverScrollViewPageContolStyleClassic;
    _hidesForSinglePage = YES;
    _currentPageDotColor = [UIColor whiteColor];
    _pageDotColor = [UIColor colorWithWhite:1 alpha:0.42];
    _bannerImageViewContentMode = UIViewContentModeScaleToFill;
    
    self.backgroundColor = [UIColor clearColor];
    self.contentOffsetX = 0;
}

+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageNamesGroup:(NSArray *)imageNamesGroup {
    WSDiscoverCoverScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
    cycleScrollView.localizationImageNamesGroup = [NSMutableArray arrayWithArray:imageNamesGroup];
    return cycleScrollView;
}

+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame shouldInfiniteLoop:(BOOL)infiniteLoop imageNamesGroup:(NSArray *)imageNamesGroup {
    WSDiscoverCoverScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
    cycleScrollView.infiniteLoop = infiniteLoop;
    cycleScrollView.localizationImageNamesGroup = [NSMutableArray arrayWithArray:imageNamesGroup];
    return cycleScrollView;
}

+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageURLStringsGroup:(NSArray *)imageURLsGroup {
    WSDiscoverCoverScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
    cycleScrollView.imageURLStringsGroup = [NSMutableArray arrayWithArray:imageURLsGroup];
    return cycleScrollView;
}

+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame delegate:(id<WSDiscoverCoverScrollViewDelegate>)delegate placeholderImage:(UIImage *)placeholderImage {
    WSDiscoverCoverScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
    cycleScrollView.delegate = delegate;
    cycleScrollView.placeholderImage = placeholderImage;
    cycleScrollView.clipsToBounds = YES;
    return cycleScrollView;
}

// 設置顯示圖片的collectionView
- (void)setupMainView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout = flowLayout;
    
    UICollectionView *mainView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
    mainView.backgroundColor = [UIColor clearColor];
    mainView.pagingEnabled = YES;
    mainView.showsHorizontalScrollIndicator = NO;
    mainView.showsVerticalScrollIndicator = NO;
    [mainView registerClass:[WSImageCell class] forCellWithReuseIdentifier:@"imageCell"];
    [mainView registerClass:[WSImageTitleCell class] forCellWithReuseIdentifier:@"imageTitleCell"];
    mainView.dataSource = self;
    mainView.delegate = self;
    mainView.scrollsToTop = NO;
    [self addSubview:mainView];
    _mainView = mainView;
}


#pragma mark - properties

- (void)setPlaceholderImage:(UIImage *)placeholderImage {
    _placeholderImage = placeholderImage;
    
    if (!self.backgroundImageView) {
        UIImageView *bgImageView = [UIImageView new];
        bgImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self insertSubview:bgImageView belowSubview:self.mainView];
        self.backgroundImageView = bgImageView;
    }
    
    self.backgroundImageView.image = placeholderImage;
}

- (void)setPageControlDotSize:(CGSize)pageControlDotSize {
    _pageControlDotSize = pageControlDotSize;
}

- (void)setShowPageControl:(BOOL)showPageControl {
    _showPageControl = showPageControl;
    
    _pageControl.hidden = !showPageControl;
}

- (void)setCurrentPageDotColor:(UIColor *)currentPageDotColor {
    _currentPageDotColor = currentPageDotColor;
    UIPageControl *pageControl = (UIPageControl *)_pageControl;
    pageControl.currentPageIndicatorTintColor = currentPageDotColor;
    
}

- (void)setPageDotColor:(UIColor *)pageDotColor {
    _pageDotColor = pageDotColor;
    
    if ([self.pageControl isKindOfClass:[UIPageControl class]]) {
        UIPageControl *pageControl = (UIPageControl *)_pageControl;
        pageControl.pageIndicatorTintColor = pageDotColor;
    }
}

- (void)setCurrentPageDotImage:(UIImage *)currentPageDotImage {
    _currentPageDotImage = currentPageDotImage;
    [self setCustomPageControlDotImage:currentPageDotImage isCurrentPageDot:YES];
}

- (void)setPageDotImage:(UIImage *)pageDotImage {
    _pageDotImage = pageDotImage;
    [self setCustomPageControlDotImage:pageDotImage isCurrentPageDot:NO];
}

- (void)setCustomPageControlDotImage:(UIImage *)image isCurrentPageDot:(BOOL)isCurrentPageDot {
    if (!image || !self.pageControl) return;
}

- (void)setInfiniteLoop:(BOOL)infiniteLoop {
    _infiniteLoop = infiniteLoop;
    
    if (self.imagePathsGroup.count) {
        self.imagePathsGroup = self.imagePathsGroup;
    }
}

-(void)setAutoScroll:(BOOL)autoScroll {
    _autoScroll = autoScroll;
    
    [self invalidateTimer];
    
    if (_autoScroll) {
        [self setupTimer];
    }
}

- (void)setScrollDirection:(UICollectionViewScrollDirection)scrollDirection {
    _scrollDirection = scrollDirection;
    
    _flowLayout.scrollDirection = scrollDirection;
}

- (void)setAutoScrollTimeInterval:(CGFloat)autoScrollTimeInterval {
    _autoScrollTimeInterval = autoScrollTimeInterval;
    
    [self setAutoScroll:self.autoScroll];
}

- (void)setPageControlStyle:(WSDiscoverCoverScrollViewPageContolStyle)pageControlStyle {
    _pageControlStyle = pageControlStyle;
    
    [self setupPageControl];
}

- (void)setImagePathsGroup:(NSArray *)imagePathsGroup {
    [self invalidateTimer];
    
    _imagePathsGroup = imagePathsGroup;
    
    _totalItemsCount = self.infiniteLoop ? self.imagePathsGroup.count * 100 : self.imagePathsGroup.count;
    
    if (imagePathsGroup.count != 1) {
        self.mainView.scrollEnabled = YES;
        [self setAutoScroll:self.autoScroll];
    } else {
        self.mainView.scrollEnabled = NO;
    }
    
    [self setupPageControl];
    [self.mainView reloadData];
}

- (void)setImageURLStringsGroup:(NSArray *)imageURLStringsGroup {
    _imageURLStringsGroup = imageURLStringsGroup;
    
    NSMutableArray *temp = [NSMutableArray new];
    [_imageURLStringsGroup enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL * stop) {
        NSString *urlString;
        if ([obj isKindOfClass:[NSString class]]) {
            urlString = obj;
        } else if ([obj isKindOfClass:[NSURL class]]) {
            NSURL *url = (NSURL *)obj;
            urlString = [url absoluteString];
        }
        if (urlString) {
            [temp addObject:urlString];
        }
    }];
    self.imagePathsGroup = [temp copy];
}

- (void)setLocalizationImageNamesGroup:(NSArray *)localizationImageNamesGroup {
    _localizationImageNamesGroup = localizationImageNamesGroup;
    self.imagePathsGroup = [localizationImageNamesGroup copy];
}

- (void)setTitlesGroup:(NSArray *)titlesGroup {
    _titlesGroup = titlesGroup;
    if (self.onlyDisplayText) {
        NSMutableArray *temp = [NSMutableArray new];
        for (int i = 0; i < _titlesGroup.count; i++) {
            [temp addObject:@""];
        }
        self.backgroundColor = [UIColor clearColor];
        self.imageURLStringsGroup = [temp copy];
    }
}

#pragma mark - actions

- (void)setupTimer {
    if (_timer) {
        [self invalidateTimer];
    }
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.autoScrollTimeInterval target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES];
    _timer = timer;
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)invalidateTimer {
    [_timer invalidate];
    _timer = nil;
}

- (void)setupPageControl {
        if (_pageControl) [_pageControl removeFromSuperview]; // 重新加載數据時調整
    
        if (self.imagePathsGroup.count == 0 || self.onlyDisplayText) return;
    
        if ((self.imagePathsGroup.count == 1) && self.hidesForSinglePage) return;
    
        int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:[self currentIndex]];
    
        switch (self.pageControlStyle) {
            case WSDiscoverCoverScrollViewPageContolStyleClassic:
            {
                UIPageControl *pageControl = [[UIPageControl alloc] init];
                pageControl.numberOfPages = self.imagePathsGroup.count;
                pageControl.currentPageIndicatorTintColor = self.currentPageDotColor;
                pageControl.pageIndicatorTintColor = self.pageDotColor;
                pageControl.userInteractionEnabled = NO;
                pageControl.currentPage = indexOnPageControl;
                [self addSubview:pageControl];
                _pageControl = pageControl;
            }
                break;
    
            default:
                break;
        }
    
        // 重設pagecontroldot圖片
        if (self.currentPageDotImage) {
            self.currentPageDotImage = self.currentPageDotImage;
        }
        if (self.pageDotImage) {
            self.pageDotImage = self.pageDotImage;
        }
}


- (void)automaticScroll {
//    NSLog(@"--------");
    if (0 == _totalItemsCount) return;
    int currentIndex = [self currentIndex];
    int targetIndex = currentIndex + 1;
    [self scrollToIndex:targetIndex];
}

- (void)scrollToIndex:(int)targetIndex {
    UICollectionViewScrollPosition scrollPosition;
    if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
        scrollPosition = UICollectionViewScrollPositionCenteredHorizontally;
    } else {
        scrollPosition = UICollectionViewScrollPositionCenteredVertically;
    }
    
    if (targetIndex >= _totalItemsCount) {
        if (self.infiniteLoop) {
            targetIndex = _totalItemsCount * 0.5;
//            [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:scrollPosition animated:NO];
            [_mainView setContentOffset:CGPointMake(targetIndex * self.itemSize.width - (CGRectGetWidth(self.mainView.frame) - self.itemSize.width) * 0.5, 0) animated:NO];
        }
        return;
    }
    //iOS14 在特定情况 scrollToItemAtIndexPath會不生效，導致始終停在0的位置，目前還不知道什麼原因，暫時先用setContentOffset代替
//    [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:scrollPosition animated:YES];
    [_mainView setContentOffset:CGPointMake(targetIndex * self.itemSize.width - (CGRectGetWidth(self.mainView.frame) - self.itemSize.width) * 0.5, 0) animated:YES];
}

- (int)currentIndex {
    if (CGRectGetWidth(_mainView.frame) == 0 || CGRectGetHeight(_mainView.frame) == 0) {
        return 0;
    }
    
    int index = 0;
    if (_flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
        float interval;
        
        if (self.dragDirection == DragDirectionNone) {
            interval = _flowLayout.itemSize.width *0.5;
        } else if (self.dragDirection == DragDirectionLeft) {
            interval = _flowLayout.itemSize.width;
        } else {
            interval = 0;
        }
        
        index = roundf(_mainView.contentOffset.x + interval) / _flowLayout.itemSize.width;
    } else {
        index = (_mainView.contentOffset.y + _flowLayout.itemSize.height) / _flowLayout.itemSize.height;
    }
//    NSLog(@"-----page:%d ----type:%d",index,self.type);
    return MAX(0, index);
}

- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index {
    return (int)index % self.imagePathsGroup.count;
}

- (void)clearCache {
    [[self class] clearImagesCache];
}

- (void)scrollerToTop {
    [self scrollViewDidEndScrollingAnimation:self.mainView];
}

+ (void)clearImagesCache {
}

#pragma mark - life circles

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _flowLayout.itemSize = self.itemSize;
    _mainView.frame = self.bounds;
    if (_mainView.contentOffset.x == 0 &&  _totalItemsCount) {
        int targetIndex = 0;
        if (self.infiniteLoop) {
            targetIndex = _totalItemsCount * 0.5;
        }else{
            targetIndex = 0;
        }
        UICollectionViewScrollPosition scrollPosition;
        if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            scrollPosition = UICollectionViewScrollPositionCenteredHorizontally;
        } else {
            scrollPosition = UICollectionViewScrollPositionCenteredVertically;
        }
//        [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:scrollPosition animated:NO];
        [_mainView setContentOffset:CGPointMake(targetIndex * self.itemSize.width - (CGRectGetWidth(self.mainView.frame) - self.itemSize.width) * 0.5, 0) animated:NO];
    }
    self.contentOffsetX = self.mainView.contentOffset.x;
    CGSize size = CGSizeZero;
    size = CGSizeMake(self.imagePathsGroup.count * self.pageControlDotSize.width * 1.5, self.pageControlDotSize.height);
    CGFloat x = (self.width - size.width) * 0.5;
    if (self.pageControlAliment == WSDiscoverCoverScrollViewPageContolAlimentRight) {
        x = self.mainView.width - size.width - 10;
    }
    CGFloat y = self.mainView.height - size.height - 10;
    CGRect pageControlFrame = CGRectMake(0, y, self.width, size.height);
    pageControlFrame.origin.y -= self.pageControlBottomOffset;
    pageControlFrame.origin.x -= self.pageControlRightOffset;
    self.pageControl.frame = pageControlFrame;
    self.pageControl.hidden = !_showPageControl;
    if (self.backgroundImageView) {
        self.backgroundImageView.frame = self.bounds;
    }
}

//解決當父View釋放時，當前视圖因為被Timer強引用而不能釋放的問題
- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview) {
        [self invalidateTimer];
    }
}

//解決當timer釋放後 回調scrollViewDidScroll時访問野指針導致崩潰
- (void)dealloc {
    _mainView.delegate = nil;
    _mainView.dataSource = nil;
}

#pragma mark - public actions

- (void)adjustWhenControllerViewWillAppera {
    long targetIndex = [self currentIndex];
    if (targetIndex < _totalItemsCount) {
        UICollectionViewScrollPosition scrollPosition;
        if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            scrollPosition = UICollectionViewScrollPositionCenteredHorizontally;
        } else {
            scrollPosition = UICollectionViewScrollPositionCenteredVertically;
        }
//        [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:scrollPosition animated:YES];
        [_mainView setContentOffset:CGPointMake(targetIndex * self.itemSize.width - (CGRectGetWidth(self.mainView.frame) - self.itemSize.width) * 0.5, 0) animated:YES];
    }
}


#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _totalItemsCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WSImageCell *cell;
    if (self.type == WSBannerCellTypeImage) {
        WSImageCell * imageCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
        cell = imageCell;
    }
    else {
        WSImageTitleCell * imageTitleCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageTitleCell" forIndexPath:indexPath];
        NSInteger row = indexPath.row % self.objectGroup.count;
        [imageTitleCell setDataWithObject:self.objectGroup[row]];
        cell = imageTitleCell;
    }
    
    
    long itemIndex = [self pageControlIndexWithCurrentCellIndex:indexPath.item];
    
    NSString *imagePath = self.imagePathsGroup[itemIndex];
    
    if ([imagePath isKindOfClass:[NSString class]]) {
        if ([imagePath hasPrefix:@"http"]) {
            [cell.bannerImageView sd_setImageWithURL:[NSURL URLWithString:imagePath]];
        } else {
            UIImage *image = [UIImage imageNamed:imagePath];
            if (!image) {
                [UIImage imageWithContentsOfFile:imagePath];
            }
            cell.bannerImageView.image = image;
        }
    } else if ([imagePath isKindOfClass:[UIImage class]]) {
        cell.bannerImageView.image = (UIImage *)imagePath;
    }
    cell.bannerView.frame = CGRectMake(self.minimumInteritemSpacing, 0, self.itemSize.width - self.minimumInteritemSpacing * 2, self.itemSize.height);
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(cycleScrollView:didSelectItemAtIndex:)]) {
        [self.delegate cycleScrollView:self didSelectItemAtIndex:[self pageControlIndexWithCurrentCellIndex:indexPath.item]];
    }
    if (self.clickItemOperationBlock) {
        self.clickItemOperationBlock([self pageControlIndexWithCurrentCellIndex:indexPath.item]);
    }
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.imagePathsGroup.count) return; // 解決清除timer時偶爾會出現的問題
    int itemIndex = [self currentIndex];
    int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex];
    UIPageControl *pageControl = (UIPageControl *)_pageControl;
    pageControl.currentPage = indexOnPageControl;
    // 圖片缩放
    if (self.zoomType) {
        if (self.mainView.contentOffset.x > self.contentOffsetX) {
            // 向左滚動
            if (self.isDragging) {
                self.dragDirection = 1;
            }
        } else {
            // 向右滚動
            if (self.isDragging) {
                self.dragDirection = 2;
            }
        }
        self.contentOffsetX = self.mainView.contentOffset.x;
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isDragging = YES;
    
    if (self.autoScroll) {
        [self invalidateTimer];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.zoomType) {
        dispatch_async(dispatch_get_main_queue(), ^{
            int index = [self currentIndex];
            [self scrollToIndex:index];
        });
    }
    
    if (self.autoScroll) {
        [self setupTimer];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    self.contentOffsetX = self.mainView.contentOffset.x;
    
    if (!self.imagePathsGroup.count) return; // 解決清除timer時偶爾會出現的問題
    int itemIndex = [self currentIndex];
    int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex];
    
    if ([self.delegate respondsToSelector:@selector(cycleScrollView:didScrollToIndex:)]) {
        [self.delegate cycleScrollView:self didScrollToIndex:indexOnPageControl];
    } else if (self.itemDidScrollOperationBlock) {
        self.itemDidScrollOperationBlock(indexOnPageControl);
    }
    
    self.isDragging = NO;
    self.dragDirection = DragDirectionNone;
}

@end
